package mango.orm;

import java.util.concurrent.CopyOnWriteArrayList;

import mango.orm.connect.Connector;
import mango.orm.impl.DBSessionImpl;

public final class DBSessionFactory {
    private static CopyOnWriteArrayList<DBSession> SESSIONS = new CopyOnWriteArrayList<DBSession>();
    private static ThreadLocal<DBSession> SESSION_POL = new ThreadLocal<DBSession>();

    public static final DBSession getCurrentSession() {
        DBSession session = DBSessionFactory.SESSION_POL.get();
        if (session == null || session.isClosed()) {
            session = new DBSessionImpl(Connector.getConnector());
            SESSIONS.add(session);
            DBSessionFactory.SESSION_POL.set(session);
        }
        return session;
    }

    public static final void closeCurrentSession() {
        DBSession session = DBSessionFactory.SESSION_POL.get();
        if (session != null && !session.isClosed()) {
            DBSessionFactory.SESSION_POL.remove();
            SESSIONS.remove(session);
            session.close();
        }
    }
    
    public static final void closeSession(DBSession session) {
        DBSession s = DBSessionFactory.SESSION_POL.get();
        if (s == session) {
            closeCurrentSession();
        }
        else {
            SESSIONS.remove(session);
            session.close();
        }
    }

    public static final DBSession getSession() {
        DBSession session = new DBSessionImpl(Connector.getConnector());
        SESSIONS.add(session);
        return session;
    }
    
    public static final DBSession getSession(Connector connector) {
        DBSession session =  new DBSessionImpl(connector);
        SESSIONS.add(session);
        return session;
    }
    
    public static final DBSession getSession(String connector) {
        DBSession session =  new DBSessionImpl(Connector.getConnector(connector));
        SESSIONS.add(session);
        return session;
    }
    
    public static final void closeAll() {
        for(DBSession s : SESSIONS) {
            closeSession(s);
        }
    }
    
    public static final int getSessionCount() {
        return SESSIONS.size();
    }
}
